package com.speechb.common;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 主页面第一页数据缓存
 *
 * @author : llj
 * @version :2.1.0
 * @date : 2020/7/5 16:23
 */
public class PagerCacheUtil {
    public static final Cache<String, Object> CACHE = CacheBuilder
            .newBuilder()
            .maximumSize(20)
            .expireAfterAccess(1, TimeUnit.DAYS)
            .build();
    final static ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();

    /**
     * 获取值
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T getValue(String key) {
        try {
            LOCK.readLock().lock();
            return (T)CACHE.getIfPresent(key);
        } finally {
            LOCK.readLock().unlock();
        }
    }

    /**
     * 存放值
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public static void  putValue(String key, Object value) {
        try {
            LOCK.writeLock().lock();
            CACHE.put(key, value);
        } finally {
            LOCK.writeLock().unlock();
        }
    }
}
